package com.baselibrary.permission;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baselibrary.permission.callback.PermissionsCall;
import com.baselibrary.permission.factory.PermissionFactory;
import com.baselibrary.utils.PopUtils;

import java.util.ArrayList;
import java.util.List;

public class PermissionsUtils {
    private static PermissionsUtils mPerUtils;
    private PermissionsCall mPermissionsCall;
    private final int PERMISSIONS_CODE = 0x0311;
    public static boolean showSystemSetting = true;
    private final PermissionFactory mPermissionFactory;
    private static final String TAG = "PermissionsUtils";

    private PermissionsUtils() {
        mPermissionFactory = new PermissionFactory();
    }


    public static PermissionsUtils getInstance() {
        if (mPerUtils == null) {
            mPerUtils = new PermissionsUtils();
        }
        return mPerUtils;
    }

    public String parsePerName(ArrayList<String> list) {
        return mPermissionFactory.perName(list);
    }

    public void chekPermissions(Activity context, String[] permissions, @NonNull PermissionsCall permissionsCall) {
        mPermissionsCall = permissionsCall;

        if (Build.VERSION.SDK_INT < 23) {//6.0才用动态权限
            permissionsCall.permissionsPass();
            return;
        }

        List<String> mPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permission);//添加还未授予的权限
            }
        }

        if (mPermissionList.size() > 0) {
            //权限申请
            ActivityCompat.requestPermissions(context, permissions, PERMISSIONS_CODE);
        } else {
            permissionsCall.permissionsPass();
        }


    }

    /**
     * @param requestCode  是我们自己定义的权限请求码
     * @param perStr       是我们请求的权限名称数组
     * @param grantResults 是我们在弹出页面后是否允许权限的标识数组，数组的长度对应的是权限名称数组的长度
     *                     数组的数据0表示允许权限，-1表示我们点击了禁止权限
     */
    public void onRequestPermissionsResult(Activity context, int requestCode,
                                           @NonNull String[] perStr, @NonNull int[] grantResults) {
        boolean isAllPass = true;
        mPermissionFactory.getPerList().clear();
        if (PERMISSIONS_CODE == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    mPermissionFactory.add(perStr[i]);
                    isAllPass = false;
                }
            }
            //如果有权限没有被允许
            if (!isAllPass) {
                if (showSystemSetting) {
                    showSystemPermissionsSettingDialog(context);
                } else {
                    mPermissionsCall.permissionsRefuse(mPermissionFactory.getPerList());
                }
            } else {
                //全部权限通过，可以进行下一步操作。。。
                mPermissionsCall.permissionsPass();
            }
        }

    }

    /**
     * 不再提示权限时的展示对话框
     */
    AlertDialog mPermissionDialog;

    private void showSystemPermissionsSettingDialog(final Activity context) {
        final String mPackName = context.getPackageName();
        if (mPermissionDialog == null) {
            if (mPermissionFactory.perName(mPermissionFactory.getPerList()).equals("位置信息")){
                //定位弹窗 特殊处理
                mPermissionDialog = PopUtils.showPermissionDialog(context, new PopUtils.ICallBack() {
                    @Override
                    public void clickOk() {
                        cancelPermissionDialog();
                        Uri packageURI = Uri.parse("package:" + mPackName);
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        context.startActivity(intent);
                    }

                    @Override
                    public void clickCancel() {
                        //关闭页面或者做其他操作
                        cancelPermissionDialog();
                        mPermissionsCall.permissionsRefuse(mPermissionFactory.getPerList());
                    }
                });
                return;
            }
            mPermissionDialog=PopUtils.showOkCancelDialog(context, "已禁用权限，请手动授予【" + mPermissionFactory.perName(mPermissionFactory.getPerList()) + "】权限", new PopUtils.ICallBack() {
                @Override
                public void clickOk() {
                    cancelPermissionDialog();
                    Uri packageURI = Uri.parse("package:" + mPackName);
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    context.startActivity(intent);
                }

                @Override
                public void clickCancel() {
                    //关闭页面或者做其他操作
                    cancelPermissionDialog();
                    mPermissionsCall.permissionsRefuse(mPermissionFactory.getPerList());
                }
            }, false, "设置", "我知道了",true);
        }
        if (!context.isFinishing()) {
            //当前界面处于前台情况下再显示
            mPermissionDialog.show();
        }
    }

    //关闭对话框
    private void cancelPermissionDialog() {
        if (mPermissionDialog != null) {
            mPermissionDialog.cancel();
            mPermissionDialog = null;
        }

    }
}
